package com.example.resource_station_backend.service.impl;


import com.example.resource_station_backend.dao.CategoryRepository;
import com.example.resource_station_backend.exception.ErrorCode;
import com.example.resource_station_backend.exception.ThrowUtils;
import com.example.resource_station_backend.model.dto.CategoryDTO;
import com.example.resource_station_backend.model.entity.Category;
import com.example.resource_station_backend.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Optional;

/**
 * @Author xinhao
 * @Description
 * @CreateTime 2025-02-25 15:53:25
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryRepository categoryRepository;

    @Override
    public String getCategoryNameById(Long categoryId) {
        Optional<Category> optionalCategory = categoryRepository.findById(categoryId);
        ThrowUtils.throwIf(optionalCategory.isEmpty(), ErrorCode.PARAMS_ERROR);
        Category category = optionalCategory.get();
        return category.getName();
    }

    @Override
    public Long getCategoryIdByName(String categoryName) {
        Optional<Category> optionalCategory = categoryRepository.findIdByName(categoryName);
        ThrowUtils.throwIf(optionalCategory.isEmpty(), ErrorCode.PARAMS_ERROR);
        Category category = optionalCategory.get();
        return category.getId();
    }

    @Override
    public Long addCategory(CategoryDTO categoryDTO) {
        if (categoryDTO.getId() == null) {
            categoryDTO.setCreated_at(LocalDateTime.now());
        }
        categoryDTO.setUpdate_at(LocalDateTime.now());
        ThrowUtils.throwIf(categoryRepository.existsByName(categoryDTO.getName()), ErrorCode.PARAMS_ERROR, "该分类已经存在");
        // DTO 转换为实体
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        // 保存
        Category savedCategory = categoryRepository.save(category);
        return savedCategory.getId();
    }


}
